package com.xiaobai.spike.service.auth.impl;

import com.xiaobai.spike.entity.User;
import com.xiaobai.spike.mapper.UserMapper;
import com.xiaobai.spike.model.response.TokenResponse;
import com.xiaobai.spike.sdk.lang.BusinessRuntimeException;
import com.xiaobai.spike.sdk.lang.Errors;
import com.xiaobai.spike.service.auth.UserService;
import com.xiaobai.spike.service.client.impl.OauthClientDetailsServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OauthClientDetailsServiceImpl.class);

    public static final String USER_LOGIN_TOKEN = "user_login_token_";

    public static final String USER_LOGIN_REFRESH_TOKEN = "user_login_refreshToken_";

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public TokenResponse login(User user) {
        if (this.checkUserLogin(user)) {
            return this.generateToken(user.getName(), null, null);
        }
       throw new BusinessRuntimeException(-1, "账号密码错误");
    }

    @Override
    public Boolean checkUserLogin(User user) {
        User name = this.getByName(user.getName());
        if (name != null) {
            return DigestUtils.md5DigestAsHex(user.getPasswd().getBytes()).equals(name.getPasswd());
        }
        return false;
    }

    @Override
    public Integer add(User user) {
        if (this.getByName(user.getName()) != null) {
            throw new BusinessRuntimeException(Errors.USER_CODE_EXITS);
        }
        user.setPasswd(DigestUtils.md5DigestAsHex(user.getPasswd().getBytes()));

        return userMapper.insert(user);
    }

    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getByName(String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("valid", 1);
        List<User> users = userMapper.selectByMap(map);
        if (CollectionUtils.isEmpty(users)) {
            return null;
        }
        return users.get(0);
    }

    @Override
    public TokenResponse generateToken(String name, Integer tokenExpire, Integer refreshTokenExpire) {
        if (tokenExpire == null) {
            tokenExpire = 7200;
        }
        if (refreshTokenExpire == null) {
            refreshTokenExpire = 14400;
        }
        String token = UUID.randomUUID().toString();
        String refreshToken = UUID.randomUUID().toString();
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccess_token(token);
        tokenResponse.setRefresh_token(refreshToken);
        tokenResponse.setToken_type("bear");
        tokenResponse.setExpires_in(tokenExpire);
        redisTemplate.opsForValue().set(USER_LOGIN_TOKEN + token, name, tokenExpire, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(USER_LOGIN_REFRESH_TOKEN + refreshToken, name, refreshTokenExpire, TimeUnit.SECONDS);
        return tokenResponse;
    }


}
